package com.ftdc.app.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceExample {

    public static void main(String[] args) {
        // 初始化 AtomicStampedReference，初始值为100，初始戳为0
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 0);

        // 创建第一个线程，尝试将值从100更新为101
        Thread thread1 = new Thread(() -> {
            int[] stampHolder = new int[1];
            Integer currentValue = atomicStampedReference.get(stampHolder); // 获取当前值和戳

            System.out.println("Thread 1: Current value: " + currentValue + ", Current stamp: " + stampHolder[0]);
            // 尝试更新值
            boolean success = atomicStampedReference.compareAndSet(currentValue, 101, stampHolder[0], stampHolder[0] + 1);
            System.out.println("Thread 1 update success: " + success);
        });

        // 创建第二个线程，尝试将值从101更新回100
        Thread thread2 = new Thread(() -> {
            int[] stampHolder = new int[1];
            Integer currentValue = atomicStampedReference.get(stampHolder); // 获取当前值和戳

            System.out.println("Thread 2: Current value: " + currentValue + ", Current stamp: " + stampHolder[0]);
            // 尝试更新值
            boolean success = atomicStampedReference.compareAndSet(currentValue, 100, stampHolder[0], stampHolder[0] + 1);
            System.out.println("Thread 2 update success: " + success);
        });

        thread1.start();
        thread2.start();

        // 等待线程结束
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 输出最终结果
        int[] finalStampHolder = new int[1];
        Integer finalValue = atomicStampedReference.get(finalStampHolder);
        System.out.println("Final value: " + finalValue + ", Final stamp: " + finalStampHolder[0]);
    }
}
